
//监听input
$(".send-photo").on("change",function (e) {
    var e = e || window.event;
    //获取 文件 个数 取消的时候使用
    var files = e.target.files;
    if(files.length>0){
        //获取当前选中的会话
        let selectedLi = document.querySelector('#session-list .selected');
        if (selectedLi == null) {
            //当前没有会话处于选中状态
            return;
        }
        let sessionId = selectedLi.getAttribute('session-id');

        var form = new FormData();
        form.append("file", files[0]);
        $.ajax({
            url: "message/savePhoto",
            type: "post",
            processData: false,
            contentType: false,
            data: form,
            success: function(result) {
                if (result.code == 200) {
                    //构造请求
                    let request = {
                        type: 1,
                        sessionId: sessionId,
                        content: result.data
                    };
                    
                    //发送请求
                    webSocket.send(JSON.stringify(request));
                }
                else if (result.code == 401) {
                    location.href = "login.html";
                }
                else {
                    alert(result.error);
                }
            }
        });
    }
});

//发送图片事件
function sendPhoto() {
    let send_photo = document.querySelector('.send-photo');
    send_photo.click();
}

//添加首页，我的，的点击事件
function initTab() {
    let hand = document.querySelector('.set .set-1');
    let self = document.querySelector('.set .set-2');

    hand.onclick = function() {
        location.href = "client.html";
    }

    self.onclick = function() {
        location.href = "set-self.html";
    }
}

initTab();

//为好友，会话图标添加点击事件
function initSwitchTab() {
    let tabSession = document.querySelector('.tab .tab-session');
    let tabFriend = document.querySelector('.tab .tab-friend');

    let lists = document.querySelectorAll('.list');
    tabSession.onclick = function() {
        tabSession.style.backgroundImage = 'url(pic/session.png)';
        tabFriend.style.backgroundImage = 'url(pic/friend1.png)';
        lists[0].classList = 'list';
        lists[1].classList = 'list hide';
    }

    tabFriend.onclick = function() {
        tabSession.style.backgroundImage = 'url(pic/session1.png)';
        tabFriend.style.backgroundImage = 'url(pic/friend.png)';
        lists[1].classList = 'list';
        lists[0].classList = 'list hide';
    }
}

initSwitchTab();
//拒绝好友申请
function falseRequest(userId) {
    $.ajax({
        type: "post",
        url: "friend/requestFalse",
        data: {
            friendId: userId
        },
        success: function(result) {
            if (result.code == 200 && result.data == true) {
                alert("已拒绝好友申请");
                //刷新申请列表
                getRequestFriend();
            }
            else if (result.code == 401) {
                location.href = "login.html";
            }
            else {
                alert(result.error);
            }
        }
    });
}

//接受好友申请
function trueRequest(userId) {
    $.ajax({
        type: "post",
        url: "friend/requestTrue",
        data: {
            friendId: userId
        },
        success: function(result) {
            if (result.code == 200 && result.data == true) {
                alert("已同意好友申请");
                location.reload(true); 
            }
            else if (result.code == 401) {
                location.href = "login.html";
            }
            else {
                alert(result.error);
            }
        }
    });
}

//获取好友申请列表
function getRequestFriend() {
    //清空消息区 
    let message = document.querySelector('.message-show');
    message.innerHTML = '';
    //清空会话名称区
    let messageTitle = document.querySelector('.right .title');
    messageTitle.innerHTML = '好友申请';

    $.ajax({
        url: "friend/getRequestFriends",
        type: "post",
        success: function(result) {
            if (result.code == 200 && result.data != null) {
                let list = result.data;
                for (let tmp of list) {
                    let div = document.createElement('div');
                    div.className = "requestUser";
                    div.innerHTML = '<div class="user-name">'
                        + tmp.sendName
                        +'</div>'
                        +'<div class="user-message">'
                        + tmp.message
                        +'</div>'
                        +'<button class="true" onclick="trueRequest('+tmp.sendId+')">接受</button>'
                        +'<button class="false" onclick="falseRequest('+tmp.sendId+')">拒绝</button>'
                    message.appendChild(div);
                }
            }
            else if (result.code == 401) {
                location.href = "login.html";
            }
            else { 
                alert(result.error);
            }
        }
    });
}

getRequestFriend();

//获取当前登录用户信息
function getUserInfo() {
    $.ajax({
        url: "user/mainUser",
        type: "get",
        success: function(result) {
            if (result.code == 200 && result.data != null) {
                let userDiv = document.querySelector(".main .left .user");
                userDiv.innerHTML = '<img src="'+result.data.photo+'" title="头像" width="50px" height="50px">'+result.data.userName;
                userDiv.setAttribute("user-id", result.data.userId);
                userDiv.setAttribute("user-name", result.data.userName);
                //给头像添加点击事件
                userDiv.onclick = function() {
                    //跳转到个人主页
                    location.href = "setUserInfo.html";
                }
            }
            else if (result.code == 401) {
                location.href = "login.html";
            }
            else {
                alert(result.error);
            }
        }
    })
}

getUserInfo();

//建群时展示好友信息
function showFriend(message, friend) {
    let userDiv = document.createElement('div');
    userDiv.className = 'group';
    userDiv.innerHTML = '<input type="checkbox" id='+friend.friendId+' name="'+friend.friendName+'">'+
        '<div class="group-name">' + friend.friendName + '</div>'
    message.appendChild(userDiv);
}

//创建群聊
function createGroup(){
    //获取所有先中的复选框
    let checkboxs = document.querySelectorAll('input[type="checkbox"]');
    let friendIds = [];
    let friendNames = [];
    for (let checkbox of checkboxs) {
        if (checkbox.checked) {
            friendIds.push(checkbox.id);
            friendNames.push(checkbox.name);
        }
    }
    //创建会话
    if (friendIds.length === 1) {
        return;
    }
    let sessionUL = document.querySelector('#session-list');
    let name = friendNames.toString();
    if (name.length > 15) {
        name = name.substring(0, 15) + '...';
    }
    let friend = {};
    friend.friendId = friendIds;
    friend.friendName = name;

    creatSession(sessionUL, friend);
    //将标签页切换到会话页面
    let tabSession = document.querySelector('.tab .tab-session');
    tabSession.click();
}

//建群按钮点击事件
function addFriendsSession() {
    //清空消息区 
    let message = document.querySelector('.message-show');
    message.innerHTML = '';
    //设置会话名称区
    let messageTitle = document.querySelector('.right .title');
    messageTitle.innerHTML = '选择群聊成员';

    $.ajax({
        type: "get",
        url: "friend/getList",
        success: function(result) {
            if (result.code == 200 && result.data != null) { 
                let data = result.data;
                for (let tmp of data) {
                    showFriend(message, tmp);
                }
                //显示建群按钮
                let button = document.createElement("button");
                button.className = "ok";
                button.onclick = function() {
                    createGroup();
                }
                button.innerHTML = '创建群聊';
                message.appendChild(button);
            }
            else if (result.code == 401) {
                location.href = "login.html";
            }
            else {
                alert(result.error);
            }
        }
    })
}

//获取好友列表
function getFeiendList() {
    $.ajax({
        type: "get",
        url: "friend/getList",
        success: function(result) {
            if (result.code == 200) {
                //清空好友列表
                let friendList = document.querySelector("#friend-list");  
                friendList.innerHTML = '';  
                //显示好友列表   
                let data = result.data;
                for (let tmp of data) {
                    let li = document.createElement('li');
                    li.innerHTML = '<h4>' + tmp.friendName + '</h4>';
                    li.setAttribute('friend-id', tmp.friendId);
                    friendList.appendChild(li);
                    //给li添加点击事件
                    li.onclick = function() {
                        //tmp用来区分点击的是谁
                        clickFriend(tmp);
                    }
                }
                //添加建群按钮
                let button = document.createElement("button");
                button.onclick = function() {
                    addFriendsSession()
                }
                button.innerHTML = '建群';
                friendList.appendChild(button);
            }
            else if (result.code == 401) {
                location.href = "login.html";
            }
            else {
                alert(result.error);
            }
        }
    })
}

getFeiendList();

function creatSession(sessionUL, friend) {
    if (friend.friendId == null || friend.friendId == "") {
        return;
    }
    let sessionLi = document.createElement('li');
    sessionLi.innerHTML = '<h3>' + friend.friendName + '</h3>'
        + '<p></p>';
    //设置置顶
    sessionUL.insertBefore(sessionLi, sessionUL.children[0]);
    //添加点击事件
    sessionLi.onclick = function() {
        clickSession(sessionLi);
    }
    //触发点击事件
    sessionLi.click();
    let id = "?";
    for (let i of friend.friendId) {
        id += 'friendId='+ i + "&";
    }
    id = id.substring(0, id.length - 1);
    
    //让服务器保存当前会话
    $.ajax({
        type: "post",
        url: "session/createSession"+id,
        success: function(result) {
            if (result.code == 200 && result.data != null) {
                console.log("创建会话成功 sessionId=" + result.data.sessionId);
                sessionLi.setAttribute('session-id', result.data.sessionId);
            }
            else if (result.code == 200) {
                console.log("创建会话失败");
            }
            else if (result.code == 401) {
                location.href = "login.html";
            }
            else {
                alert(result.error);
            }
        }
    })
}

//点击发送按钮发送消息
function sendMessage() {
    let input = document.querySelector('.right .message-input');
    if (!input.value) {
        //输入框为空，不发送消息（value的值为null或空）
        return;
    }
    //获取当前选中的会话
    let selectedLi = document.querySelector('#session-list .selected');
    if (selectedLi == null) {
        //当前没有会话处于选中状态
        return;
    }
    let sessionId = selectedLi.getAttribute('session-id');
    //构造请求
    let request = {
        type: 0,
        sessionId: sessionId,
        content: input.value
    };
    //发送请求
    webSocket.send(JSON.stringify(request));
    //清空输入框
    input.value = '';
}

//点击好友的事件
function clickFriend(friend) {
    //显示右侧消息发送区域
    let input = document.querySelector('.message-input');
    input.classList = 'message-input';
    input.removeAttribute('readonly');
    input.setAttribute('style', 'border-top: 1px solid #ccc');
    let send = document.querySelector('.send');
    send.classList = 'send';
    let send_message = document.querySelector('.send-message');
    send_message.classList = 'send-message';
    send_message.onclick = function () {
        sendMessage();
    };
    let send_phone = document.querySelector('.send-photo-tab');
    send_phone.classList = 'send-photo-tab';
    send_phone.onclick = function () {
        sendPhoto();
    };
    //获取所有的会话
    let sessionList = document.querySelectorAll('#session-list>li');
    let sessionLi = null;
    for (let li of sessionList) {
        if (friend.friendName == li.querySelector('h3').innerHTML) {
            sessionLi = li;
            break;
        } 
    }
    let sessionUL = document.querySelector('#session-list');
    //如果当前好友存在会话，则直接进入会话页面
    if (sessionLi != null) {
        //设置置顶
        sessionUL.insertBefore(sessionLi, sessionUL.children[0]);
        //获取历史消息设置高亮
        clickSession(sessionLi);
    }
    else {
        //创建会话
        friend.friendId = [friend.friendId];
        creatSession(sessionUL, friend);
    }
    //将标签页切换到会话页面
    let tabSession = document.querySelector('.tab .tab-session');
    tabSession.click();
}

//获取会话列表
function getSessionList() {
    $.ajax({
        type: "get",
        url: "session/getMessageSession",
        success: function(result) {
            //清空之前的会话列表
            let sessionList = document.querySelector("#session-list");
            sessionList.innerHTML = '';
            if (result.code == 200) {
                //显示会话列表
                let data = result.data;
                for (let tmp of data) {
                    if (tmp.lastMessage != null && tmp.lastMessage.length > 10) {
                        tmp.lastMessage = tmp.lastMessage.substring(0, 10) + '...'
                    }
                    let li = document.createElement('li');
                    let name = tmp.name;
                    if (name == "") {
                        name = tmp.friend[0].userName;
                        alert(name)
                    }
                    
                    if (tmp.type == 1) {
                        tmp.lastMessage = "[图片]";
                    }
                    li.innerHTML = '<h3>' + name + '</h3>'
                        + '<p>' + tmp.lastMessage + '</p>';
                    li.setAttribute('session-id', tmp.sessionId);
                    //设置该会话暂时最多显示多少条消息
                    li.setAttribute('max-message', 0);
                    sessionList.appendChild(li); 
                    //给li添加点击  
                    li.onclick = function() {
                        clickSession(li);
                    }
                }
            }
            else if (result.code == 401) {
                location.href = "login.html";
            }
            else {
                alert(result.error);
            }

        }
    })
}

getSessionList();

//点击会话，获取历史消息设置高亮
function clickSession(session) {
    //显示右侧消息发送区域
    let input = document.querySelector('.message-input');
    input.classList = 'message-input';
    input.removeAttribute('readonly');
    input.setAttribute('style', 'border-top: 1px solid #ccc');
    let send = document.querySelector('.send');
    send.classList = 'send';
    let send_message = document.querySelector('.send-message');
    send_message.classList = 'send-message';
    send_message.onclick = function () {
        sendMessage();
    };
    let send_phone = document.querySelector('.send-photo-tab');
    send_phone.classList = 'send-photo-tab';
    send_phone.onclick = function () {
        sendPhoto();
    };
    //设置高亮
    let allLis = document.querySelectorAll('#session-list>li');
    activeSession(allLis, session);
    //获取历史消息
    getHistoryMessage(session);
}
//将当前被点击的会话设置高亮，其余会话取消高亮设置
function activeSession(allLis, currentLi) {
    for (let li of allLis) {
        if (li == currentLi) {
            li.className = 'selected';
        } else {
            li.className = '';
        }
    }
}

//清空消息区并设置会话名称
function clearMessage(message) {
    message.innerHTML = '';
    //清空会话名称区
    let messageTitle = document.querySelector('.right .title');
    messageTitle.innerHTML = '';
    //设置会话名称
    let title = document.querySelector('#session-list .selected>h3');
    messageTitle.innerHTML = title.innerHTML;
}


//获取历史消息
function getHistoryMessage(session) {
    session.setAttribute('max-message', 0);
    //清空消息区 
    let message = document.querySelector('.message-show');
    clearMessage(message);
    //获取历史消息
    $.ajax({
        type: "get",
        url: "message/getHistoryMessage",
        data: {
            sessionId: session.getAttribute('session-id'),
            start: session.getAttribute('max-message'),
        },
        success: function(result) {
            if (result.code == 200 && result.data != null) {
                let datas = result.data;
                //将消息显示在界面
                for (let data of datas) {
                    addMessage(message, data);
                    //设置消息区滚动条到底部
                    message.scrollTop = message.scrollHeight;
                    session.setAttribute('max-message', 1 + parseInt(session.getAttribute('max-message')) );
                }
            }
            else if (result.code == 200) {
                alert("没有更多消息了");
            }
            else if (result.code == 401) {
                location.href = "login.html";
            }
            else if (result.code == 500) {
                alert(result.error);
            }
        }
    })
}

//将消息显示在界面最上方
function addMessage(message, data) {
    //表示一条消息
    let messageDiv = document.createElement('div');
    let selfUserName = document.querySelector('.left .user').getAttribute('user-name');
    //判断消息的发送人
    if (selfUserName == data.userName) {
        //是自己发的，靠右
        messageDiv.className = 'message message-right';
    }
    else {
        //别人发的，靠左
        messageDiv.className = 'message message-left';
    }
    if (data.type == 0) {
        messageDiv.innerHTML = '<div class="box">'
            + '<h4>' + data.userName + '</h4>'
            + '<p>' + data.content + '</p>'
            + '</div>';
    } else {
        messageDiv.innerHTML = '<div class="box">'
            + '<h4>' + data.userName + '</h4>'
            + '<p><img src="'+data.content+'" onload="if(this.width>=200){this.width=200}"></p>'
            + '</div>';
    }
    //让该条消息置顶
    message.prepend(messageDiv);
}

//将消息显示在界面最下方
function addEndMessage(message, data) {
    //表示一条消息
    let messageDiv = document.createElement('div');
    let selfUserName = document.querySelector('.left .user').getAttribute('user-name');
    //判断消息的发送人
    if (selfUserName == data.userName) {
        //是自己发的，靠右
        messageDiv.className = 'message message-right';
    }
    else {
        //别人发的，靠左
        messageDiv.className = 'message message-left';
    }
    if (data.type == 0) {
        messageDiv.innerHTML = '<div class="box">'
            + '<h4>' + data.userName + '</h4>'
            + '<p>' + data.content + '</p>'
            + '</div>';
    } else {
        messageDiv.innerHTML = '<div class="box">'
            + '<h4>' + data.userName + '</h4>'
            + '<p><img src="'+data.content+'" onload="if(this.width>=200){this.width=200}"></p>'
            + '</div>';
    }
    
    //让该条消息置底
    message.appendChild(messageDiv);
}

//点击加载按钮获取历史消息
function loadMessage() {
    //获取当前的会话
    let selected = document.querySelector('#session-list .selected');
    let message = document.querySelector('.message-show');
    $.ajax({
        type: "get",
        url: "message/getHistoryMessage",
        data: {
            sessionId: selected.getAttribute('session-id'),
            start: selected.getAttribute('max-message'),
        },
        success: function(result) {
            if (result.code == 200 && result.data != null && result.data.length != 0) {
                let datas = result.data;
                //将消息显示在界面
                for (let data of datas) {
                    addMessage(message, data);
                    selected.setAttribute('max-message', 1 + parseInt(selected.getAttribute('max-message')) );
                }
            }
            else if (result.code == 200) {
                alert("没有更多消息了");
            }
            else if (result.code == 401) {
                location.href = "login.html";
            }
            else if (result.code == 500) {
                alert(result.error);
            }
        }
    })
}

//WebSocket 连接
let webSocket = new WebSocket('ws://'+location.host+'/wsMessage');
webSocket.onopen = function() {
    console.log("WebSocket 连接成功");
}

webSocket.onmessage = function(event) {
    console.log("WebSocket 收到消息：" + event.data);
    //解析消息
    let message = JSON.parse(event.data);
    //是消息,展示在会话预览区及消息列表
    //获取所有会话列表
    let sessionList = document.querySelectorAll('#session-list li');
    let sessionLi = null;
    for (let li of sessionList) {
        if (li.getAttribute('session-id') == message.sessionId) {
            //找到了对应的会话
            sessionLi = li;
        }
    }
    if (sessionLi == null) {
        //如果会话不存在就创建一个新的
        sessionLi = document.createElement('li');
        sessionLi.setAttribute('session-id', message.sessionId);
        sessionLi.innerHTML = '<h3>' + message.userName + '</h3>'
            + '<p></p>';
        sessionLi.onclick = function() {
            clickSession(sessionLi);
        }
    }
    //将消息添加在会话的消息预览区
    let p = sessionLi.querySelector('p');
    if (message.type == 0) {
        p.innerHTML = message.content;
    } else {
        p.innerHTML = "[图片]"
    }
    if (p.innerHTML.length > 8) {
        p.innerHTML = p.innerHTML.substring(0, 8) + '...';
    }
    //将会话置顶
    let sessionUL = document.querySelector('#session-list');
    sessionUL.insertBefore(sessionLi, sessionUL.children[0]);
    //判断会话是否被选中
    if (sessionLi.className == 'selected') {
        let messageShow = document.querySelector('.message-show');
        //如果当前会话处于选中状态，则将消息添加到消息列表
        addEndMessage(messageShow, message);
        //设置消息区滚动条到底部
        messageShow.scrollTop = messageShow.scrollHeight;
    }
}

webSocket.onclose = function() {
    console.log("WebSocket 连接关闭");
}
webSocket.onerror = function() {
    console.log("WebSocket 连接出错");
}

//搜索用户
function search() {
    let input = document.getElementById('search-input');
    //清空会话区
    let message = document.querySelector('.message-show');
    message.innerHTML = '';
    let messageTitle = document.querySelector('.right .title');
    messageTitle.innerHTML = '';
    $.ajax({
        type: "get",
        url: "user/searchByName",
        data: {
            userName: input.value
        },
        success: function(result) {
            if (result.code == 200 && result.data != null) {
                for (let user of result.data) {
                    showUserInfo(message, user);
                }
            }
            else if (result.code == 200 && result.data == null) {
                alert("用户不存在");
            }
            else if (result.code == 401) {
                location.href = "login.html";
            }
            else {
                alert(result.error);
            }
        }
    });
}

//请求添加好友
function requestUser(userId) {
    let input = document.getElementById('add-user');
    $.ajax({
        type: "post",
        url: "friend/requestAdd",
        data: {
            friendId: userId,
            message: input.value
        },
        success: function(result) {
            if (result.code == 200 && result.data == true) {
                alert("已发送好友申请，等待对方处理");
            }
            else if (result.code == 401) {
                location.href = "login.html";
            }
            else{
                alert(result.error);
            }
        }
    });
}

//将用户信息显示在右侧区域
function showUserInfo(messageShow, user) {
    let userDiv = document.createElement('div');
    userDiv.className = 'user-info';
    if (user.userId != 0) {
        userDiv.innerHTML = '<div class="user-name">'+user.userName+'</div>'
        +'<input type = "text" id = "add-user" placeholder="打个招呼">'
        +'<button onclick="requestUser('+user.userId+')">添加好友</button>';
    }
    else {
        userDiv.innerHTML = '<div class="user-name">'+user.userName+'</div>';
    }
    messageShow.appendChild(userDiv);
}